package org.example.lotterysystem.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.lotterysystem.common.pojo.CommonResult;
import org.example.lotterysystem.common.utils.JacksonUtil;
import org.example.lotterysystem.controller.param.DrawPrizeParam;
import org.example.lotterysystem.controller.param.ShowWinningRecordsParam;
import org.example.lotterysystem.controller.result.WinningRecordsResult;
import org.example.lotterysystem.service.DrawPrizeService;
import org.example.lotterysystem.service.dto.WinningRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    //异步抽奖
    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param) {
        log.info("drawPrize DrawPrizeParam:{}", param);
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showWinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param) {
        log.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO> winningRecordDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordResultList(winningRecordDTOList));
    }

    private List<WinningRecordsResult> convertToWinningRecordResultList(List<WinningRecordDTO> winningRecordDTOList) {
        if(CollectionUtils.isEmpty(winningRecordDTOList)) {
            return Arrays.asList();
        }
        return winningRecordDTOList.stream()
                .map(winningRecordDTO -> {
                    WinningRecordsResult winningRecordsResult = new WinningRecordsResult();
                    winningRecordsResult.setWinnerId(winningRecordDTO.getWinnerId());
                    winningRecordsResult.setWinnerName(winningRecordDTO.getWinnerName());
                    winningRecordsResult.setPrizeName(winningRecordDTO.getPrizeName());
                    winningRecordsResult.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
                    winningRecordsResult.setWinningTime(winningRecordDTO.getWinningTime());
                    return winningRecordsResult;
                }).collect(Collectors.toList());
    }
}
